/**
 * 
 */
package com.google.code.onlineshopping4j.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.onlineshopping4j.exception.OnlineShoppingException;
import com.google.code.onlineshopping4j.exception.ProductNotFoundExcpetion;
import com.google.code.onlineshopping4j.service.DashBoardService;

/**
 * @author TelmilaJ
 *
 */
@Controller
public class WelcomeController {
	
	
	public static final String WELCOME_REQUEST_MAPPING_EMPTY_SLASH = "/";
	public static final String WELCOME_REQUEST_MAPPING_INDEX = "/index";
	
	public static final String WELCOME_VIEW_NAME = "index";
	
	private Logger logger = LoggerFactory.getLogger(WelcomeController.class);
	
	@Autowired
	private DashBoardService dashBoardService;
	
	@RequestMapping(value={WELCOME_REQUEST_MAPPING_EMPTY_SLASH, 
			WELCOME_REQUEST_MAPPING_INDEX})
	public String welcome(ModelMap model, HttpSession session){
		try {
			model.addAttribute("products", dashBoardService.getAllProduct());
		} catch (OnlineShoppingException exp) {
			logger.warn(exp.getMessage());
		} catch (Exception exp) {
			logger.warn(exp.getMessage());
		}
		return WELCOME_VIEW_NAME;
	}
	
	@RequestMapping(value="aboutus")
	public String aboutus(){
		return "aboutus";
	}
	@RequestMapping(value="contactus")
	public String contactus(){
		return "contactus";
	}
	
	@RequestMapping(value="addToCard", method=RequestMethod.GET)
	public @ResponseBody Boolean getProductById(@RequestParam("productId") Long productId, 
			@RequestParam(value="quantity", required=false) Integer quantity,
			HttpSession session) throws ProductNotFoundExcpetion {
		Map<Long, Integer> cardItem = (Map<Long, Integer>)session.getAttribute("cardItems");
		if (cardItem == null) {
			cardItem = new LinkedHashMap<Long, Integer>();
		}
		if (quantity == null) {
			quantity = 250;
		}
		cardItem.put(productId, quantity);
		session.setAttribute("cardItems", cardItem);
		return Boolean.TRUE;
	}
}
